-- to_layer
-- Created by chengb Sep/11/2015
-- 成就：达成迷宫层数

-- 内部函数声明
local whenNextFloor;

-- 关注玩家进入下一层的回调
EventMgr.register("game_achievement/to_layer", event.NEXT_FLOOR, function()
    whenNextFloor();
end);

-- 关注玩家进入下一层的回调
whenNextFloor = function()
    local layer = DungeonM.currentLayer();

    local pet = ME.user:getActivePet();
    if not pet then
        return;
    end

    -- 获取所属阵营
    local campId = CampM.getPetCamp(pet.classId);

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["layer"]) == 'number' and
               ruleArg["layer"] ~= layer then
                -- 层数不匹配
                return false;
            end

            if type(ruleArg["camp_id"]) == 'number' and
               ruleArg["camp_id"] ~= campId then
                -- 没有使用规定阵营的冈布奥
                return false;
            end
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("to_layer");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local layer   = ruleArg["layer"];
        local desc    = config["desc"];
        local campId  = ruleArg["camp_id"];

        desc = string.gsub(desc, "{camp}", CampM.query(campId, "name"));
        desc = string.gsub(desc, "{layer}", layer);

        return desc;
    end,
};